package com.zenithmind.note.controller;

import com.zenithmind.common.annotation.Log;
import com.zenithmind.common.constant.OperationTypeEnum;
import com.zenithmind.common.result.PageResult;
import com.zenithmind.common.result.Result;
import com.zenithmind.note.pojo.dto.NoteDTO;
import com.zenithmind.note.pojo.query.NoteQuery;
import com.zenithmind.note.pojo.vo.NoteVO;
import com.zenithmind.note.pojo.vo.NoteTagVO;
import com.zenithmind.note.service.NoteService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.zenithmind.note.pojo.entity.Note;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.HashMap;

/**
 * 笔记控制器
 * 重构后遵循面向对象设计原则：
 * 1. 单一职责：只负责笔记的基本CRUD操作
 * 2. 依赖倒置：依赖抽象而非具体实现
 * 3. 接口隔离：将不同功能分离到不同的控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/zenithMind/note")
@RequiredArgsConstructor
@Tag(name = "笔记管理")
public class NoteController {

    private final NoteService noteService;
    
    /**
     * 创建笔记
     */
    @Log(description = "创建笔记", operationType = OperationTypeEnum.ADD)
    @PostMapping("/createNote")
    @Operation(summary = "创建笔记")
    public Result<Note> createNote(@Validated @RequestBody NoteDTO noteDTO) {
        log.info("创建笔记：{}", noteDTO);
        return Result.success(noteService.createNote(noteDTO));
    }
    
    /**
     * 更新笔记
     */
    @Log(description = "更新笔记", operationType = OperationTypeEnum.UPDATE)
    @PutMapping("/updateNote")
    @Operation(summary = "更新笔记")
    public Result<Void> updateNote(@Validated @RequestBody NoteDTO noteDTO) {
        log.info("更新笔记：{}", noteDTO);
        noteService.updateNote(noteDTO);
        return Result.success();
    }
    
    /**
     * 删除笔记
     */
    @Log(description = "删除笔记", operationType = OperationTypeEnum.DELETE)
    @DeleteMapping("/deleteNote/{id}")
    @Operation(summary = "删除笔记")
    public Result<Void> deleteNote(@PathVariable String id) {
        log.info("删除笔记：{}", id);
        noteService.deleteNote(id);
        return Result.success();
    }
    
    /**
     * 获取笔记详情
     */
    @Log(description = "获取笔记详情", operationType = OperationTypeEnum.QUERY)
    @GetMapping("/getNoteDetail/{id}")
    @Operation(summary = "获取笔记详情")
    public Result<NoteVO> getNoteDetail(@PathVariable String id) {
        log.info("获取笔记详情：{}", id);
        return Result.success(noteService.getNoteDetail(id));
    }
    
    /**
     * 分页查询笔记列表
     */
    @Log(description = "分页查询笔记列表", operationType = OperationTypeEnum.QUERY)
    @GetMapping("/notePage")
    @Operation(summary = "分页查询笔记列表")
    public Result<PageResult<NoteVO>> notePage(NoteQuery query) {
        log.info("分页查询笔记列表：{}", query);
        // 校验参数
        if (query.getCurrent() == null || query.getCurrent() < 1) {
            query.setCurrent(1);
        }
        if (query.getSize() == null || query.getSize() < 1) {
            query.setSize(10);
        }
        return Result.success(noteService.notePage(query));
    }
    
    /**
     * 获取标签列表
     */
    @Log(description = "获取标签列表", operationType = OperationTypeEnum.QUERY)
    @GetMapping("/tags")
    @Operation(summary = "获取标签列表")
    public Result<List<Map<String, Object>>> getTags() {
        log.info("获取标签列表");
        // 从数据库中获取标签列表及使用统计
        List<Map<String, Object>> tags = noteService.getTagsWithCount();
        return Result.success(tags);
    }
    

    
    /**
     * 点赞/取消点赞笔记
     */
    @Log(description = "点赞/取消点赞笔记", operationType = OperationTypeEnum.UPDATE)
    @PostMapping("/toggleNoteLike/{noteId}")
    @Operation(summary = "点赞/取消点赞笔记")
    public Result<Boolean> toggleNoteLike(@PathVariable String noteId) {
        log.info("点赞/取消点赞笔记：{}", noteId);
        noteService.toggleLike(noteId);
        return Result.success(true);
    }
    
    /**
     * 获取已发布笔记数量
     */
    @Log(description = "获取已发布笔记数量", operationType = OperationTypeEnum.QUERY)
    @GetMapping("/countPublishedNotes")
    @Operation(summary = "获取已发布笔记数量")
    public Result<Map<String, Object>> countPublishedNotes() {
        log.info("获取已发布笔记数量");
        NoteQuery query = new NoteQuery();
        query.setStatus(1); // 1表示已发布状态
        query.setCurrent(1);
        query.setSize(1);
        
        // 只获取总数
        PageResult<NoteVO> pageResult = noteService.notePage(query);
        
        Map<String, Object> result = new HashMap<>();
        result.put("total", pageResult.getTotal());
        
        return Result.success(result);
    }
    
    /**
     * 更新笔记状态
     */
    @Log(description = "更新笔记状态", operationType = OperationTypeEnum.UPDATE)
    @PutMapping("/updateNoteStatus/{id}")
    @Operation(summary = "更新笔记状态")
    public Result<Void> updateStatus(@PathVariable String id, @RequestParam Integer status) {
        log.info("更新笔记状态：id={}, status={}", id, status);
        // 通过批量更新状态方法实现
        noteService.batchUpdateStatus(List.of(id), status);
        return Result.success();
    }
    
    /**
     * 批量删除笔记（管理功能）
     */
    @Log(description = "批量删除笔记", operationType = OperationTypeEnum.DELETE)
    @DeleteMapping("/deleteBatchNotes")
    @Operation(summary = "批量删除笔记-管理功能")
    public Result<Boolean> deleteBatchNotes(@RequestBody List<String> ids) {
        log.info("批量删除笔记：{}", ids);
        noteService.deleteBatch(ids);
        return Result.success(true);
    }
    
    /**
     * 批量更新笔记状态（管理功能）
     */
    @Log(description = "批量更新笔记状态", operationType = OperationTypeEnum.UPDATE)
    @PutMapping("/updateBatchStatus")
    @Operation(summary = "批量更新笔记状态-管理功能")
    public Result<Void> batchUpdateStatus(@RequestParam String ids, @RequestParam Integer status) {
        log.info("批量更新笔记状态：ids={}, status={}", ids, status);
        List<String> idList = Arrays.stream(ids.split(","))
                .collect(Collectors.toList());
        noteService.batchUpdateStatus(idList, status);
        return Result.success();
    }
    
    /**
     * 分页查询笔记列表（管理功能）
     */
    @Log(description = "管理端分页查询笔记列表", operationType = OperationTypeEnum.QUERY)
    @GetMapping("/noteManagePage")
    @Operation(summary = "分页查询笔记列表-管理功能")
    public Result<PageResult<NoteVO>> noteManagePage(NoteQuery query) {
        log.info("管理端分页查询笔记列表：{}", query);
        // 校验参数
        if (query.getCurrent() == null || query.getCurrent() < 1) {
            query.setCurrent(1);
        }
        if (query.getSize() == null || query.getSize() < 1) {
            query.setSize(10);
        }
        return Result.success(noteService.notePage(query));
    }
    
    /**
     * 获取笔记详情（管理功能）
     */
    @Log(description = "管理端获取笔记详情", operationType = OperationTypeEnum.QUERY)
    @GetMapping("/getNoteById")
    @Operation(summary = "获取笔记详情-管理功能")
    public Result<NoteVO> getNoteById(@RequestParam("noteId") String noteId) {
        log.info("管理端获取笔记详情：{}", noteId);
        return Result.success(noteService.getNoteDetail(noteId));
    }

    /**
     * 添加或修改笔记（管理功能）
     */
    @Log(description = "添加或修改笔记", operationType = OperationTypeEnum.UPDATE)
    @PostMapping("/addOrUpdateNote")
    @Operation(summary = "添加或修改笔记-管理功能")
    public Result<NoteVO> addOrUpdateNote(@RequestBody Note note) {
        log.info("添加或修改笔记：{}", note);
        NoteVO noteVO = noteService.addOrUpdateNoteByAdmin(note);
        return Result.success(noteVO);
    }
    
    /**
     * 获取笔记的标签列表
     */
    @Log(description = "获取笔记的标签列表", operationType = OperationTypeEnum.QUERY)
    @GetMapping("/getNoteTagList/{noteId}")
    @Operation(summary = "获取笔记的标签列表")
    public Result<List<NoteTagVO>> getNoteTagList(@PathVariable String noteId) {
        log.info("获取笔记的标签列表：{}", noteId);
        return Result.success(noteService.getNoteTagList(noteId));
    }
    

    

} 